#include <stdlib.h>
#include "bc.h"

#define MAXOP 100

int getop(char []);

int main()
{
    char s[MAXOP];
    int type;           // input type
    int pos = 0;        // position of the operator
    int negative = 0;   // negative number signal
    double op1, op2;

    printf("***** Calculator *****\n");
    printf("(Input EOF to exit)\n\n");

    while ((type = getop(s)) != EOF) {
        switch (type) {
            case NUMBER:
                pos++;
                if (!negative)
                    push(atof(s));
                else {
                    push(-atof(s));
                    negative = 0;
                    pos--;
                }
                break;
            case '+':
                pos++;
                push(pop() + pop());
                break;
            case '*':
                pos++;
                push(pop() * pop());
                break;
            case '-':
                pos++;
                if (pos == 3) {
                    op2 = pop();
                    push(pop() - op2);
                } else {
                    negative = 1;
                }
                break;
            case '/':
                pos++;
                op2 = pop();
                if (op2 != 0.0)
                    push(pop() / op2);
                else
                    fprintf(stderr, "error: zero divisor\n");
                break;
            case '%':
                pos++;
                op2 = pop();
                op1 = pop();
                if (isintger(op2) && isintger(op2)) 
                    push((int)op1 % (int)op2);
                else
                    fprintf(stderr, "error: operator is not a intger\n");
                break;
            case '\n':
                pos = 0;
                printf("==> %.8g\n", pop());
                break;
            default:
                fprintf(stderr, "error: unknown command\n");
                break;
        }
    }
    return 0;
}
